import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:drift/drift.dart';
import 'package:dio/dio.dart';

import '../../data/database/app_database.dart';
import '../../data/datasources/remote/project_api_service.dart';
import '../../data/datasources/remote/auth_api_service.dart';
import '../../data/datasources/remote/note_api_service.dart'; // 添加笔记API服务
import '../../data/datasources/remote/todo_api_service.dart'; // 添加待办API服务
import '../connectivity/connectivity_service.dart';
import './offline_sync_service.dart'; // 添加离线同步服务

/// 数据同步状态枚举
enum SyncStatus {
  idle, // 空闲
  syncing, // 同步中
  completed, // 同步完成
  failed // 同步失败
}

/// 数据同步服务
class DataSyncService {
  static final DataSyncService _instance = DataSyncService._internal();
  factory DataSyncService() => _instance;
  DataSyncService._internal();

  // 依赖的服务
  late AppDatabase _database;
  late ProjectApiService _projectApiService;
  late AuthApiService _authApiService;
  late NoteApiService _noteApiService; // 添加笔记API服务
  late TodoApiService _todoApiService; // 添加待办API服务
  late ConnectivityService _connectivityService;
  late OfflineSyncService _offlineSyncService; // 添加离线同步服务

  // 同步状态控制器
  final StreamController<SyncStatus> _syncStatusController =
      StreamController<SyncStatus>.broadcast();
  Stream<SyncStatus> get syncStatus => _syncStatusController.stream;
  SyncStatus _currentStatus = SyncStatus.idle;
  SyncStatus get currentStatus => _currentStatus;

  // 同步进度控制器
  final StreamController<double> _progressController =
      StreamController<double>.broadcast();
  Stream<double> get syncProgress => _progressController.stream;

  bool _isInitialized = false;

  /// 初始化服务
  Future<void> initialize({
    required AppDatabase database,
    required ProjectApiService projectApiService,
    required AuthApiService authApiService,
    required NoteApiService noteApiService, // 添加笔记API服务
    required TodoApiService todoApiService, // 添加待办API服务
    required ConnectivityService connectivityService,
    required OfflineSyncService offlineSyncService, // 添加离线同步服务
  }) async {
    if (_isInitialized) return;

    _database = database;
    _projectApiService = projectApiService;
    _authApiService = authApiService;
    _noteApiService = noteApiService; // 初始化笔记API服务
    _todoApiService = todoApiService; // 初始化待办API服务
    _connectivityService = connectivityService;
    _offlineSyncService = offlineSyncService; // 初始化离线同步服务

    // 监听网络状态变化
    _connectivityService.connectionStatus.listen(_onConnectionStatusChanged);

    _isInitialized = true;
  }

  /// 网络状态变化回调
  void _onConnectionStatusChanged(ConnectivityResult result) {
    if (result != ConnectivityResult.none) {
      // 网络连接恢复，尝试同步数据
      syncAllData();
    }
  }

  /// 同步所有数据
  Future<void> syncAllData() async {
    if (!_isInitialized || _currentStatus == SyncStatus.syncing) return;

    _updateStatus(SyncStatus.syncing);
    _updateProgress(0.0);

    try {
      // 1. 同步用户数据
      await _syncUsers();
      _updateProgress(0.2);

      // 2. 同步项目数据
      await _syncProjects();
      _updateProgress(0.4);

      // 3. 同步待办事项数据
      await _syncTodos();
      _updateProgress(0.6);

      // 4. 同步笔记数据
      await _syncNotes();
      _updateProgress(0.8);

      // 5. 同步离线操作
      await _syncOfflineOperations();
      _updateProgress(0.9);

      // 6. 清理已同步的数据
      await _cleanupSyncedData();
      _updateProgress(1.0);

      _updateStatus(SyncStatus.completed);
    } on DioException catch (e) {
      debugPrint('数据同步失败，网络错误: $e');
      // 特别处理连接错误
      if (e.type == DioExceptionType.connectionError) {
        debugPrint('网络连接错误，请检查网络设置或稍后重试');
      }
      _updateStatus(SyncStatus.failed);
    } catch (e) {
      debugPrint('数据同步失败: $e');
      _updateStatus(SyncStatus.failed);
    }
  }

  /// 同步用户数据
  Future<void> _syncUsers() async {
    try {
      // 获取当前用户信息
      final response = await _authApiService.getCurrentUser();
      if (response.success && response.data != null) {
        final userInfo = response.data!;
        final user = userInfo.toUserModel().copyWith(
              updateTime: DateTime.now(),
            );

        // 转换为数据库兼容的格式并插入或更新本地数据库
        final userCompanion = UsersCompanion(
          id: Value(user.id),
          username: Value(user.username),
          email: Value(user.email),
          role: Value(user.role),
          isActive: Value(user.isActive),
          createTime: Value(user.createTime),
          updateTime: Value(user.updateTime ?? DateTime.now()),
        );
        await _database.insertUser(userCompanion);
      }
    } catch (e) {
      debugPrint('同步用户数据失败: $e');
      rethrow;
    }
  }

  /// 同步项目数据
  Future<void> _syncProjects() async {
    try {
      // 获取我的项目列表
      final response = await _projectApiService.getMyProjects();
      if (response.success && response.data != null) {
        final projects = response.data!;

        // 批量插入或更新本地数据库
        for (final project in projects) {
          final projectCompanion = ProjectsCompanion(
            id: Value(project.id),
            projectName: Value(project.projectName),
            description: Value(project.description),
            status: Value(project.status.code),
            ownerId: Value(project.creatorId),
            createTime: Value(project.createTime),
            updateTime: Value(project.updateTime ?? DateTime.now()),
          );
          await _database.insertProject(projectCompanion);
        }
      }
    } catch (e) {
      debugPrint('同步项目数据失败: $e');
      rethrow;
    }
  }

  /// 同步待办事项数据
  Future<void> _syncTodos() async {
    try {
      // 获取所有待办事项
      // 这里可以根据需要分页获取
      final response = await _todoApiService.getTodos();
      if (response.success && response.data != null) {
        final todos = response.data!;

        // 批量插入或更新本地数据库
        for (final todo in todos) {
          final todoCompanion = TodosCompanion(
            id: Value(todo.id),
            title: Value(todo.title),
            description: Value(todo.description),
            status: Value(todo.status.code),
            projectId: Value(todo.projectId),
            assigneeId: Value(todo.assigneeId),
            reporterId: Value(todo.reporterId),
            estimatedHours: Value(todo.estimatedHours?.toInt()),
            actualHours: Value(todo.actualHours?.toInt()),
            createTime: Value(todo.createTime),
            updateTime: Value(todo.updateTime ?? DateTime.now()),
            dueDate: Value(todo.dueDate),
          );
          await _database.insertTodo(todoCompanion);
        }
      }
    } catch (e) {
      debugPrint('同步待办事项数据失败: $e');
      rethrow;
    }
  }

  /// 同步笔记数据
  Future<void> _syncNotes() async {
    try {
      // 获取所有笔记
      // 这里可以根据需要分页获取
      final response = await _noteApiService.getNotes();
      if (response.success && response.data != null) {
        final notes = response.data!;

        // 批量插入或更新本地数据库
        for (final note in notes) {
          final noteCompanion = NotesCompanion(
            id: Value(note.id),
            projectId: Value(note.projectId),
            todoId: Value(note.todoId),
            title: Value(note.title),
            content: Value(note.content),
            noteType: Value(note.noteType.code),
            tags: Value(note.tags.join(',')),
            authorId: Value(note.authorId),
            isPublic: Value(note.isPublic),
            createTime: Value(note.createTime),
            updateTime: Value(note.updateTime ?? DateTime.now()),
          );
          await _database.insertNote(noteCompanion);
        }
      }
    } catch (e) {
      debugPrint('同步笔记数据失败: $e');
      rethrow;
    }
  }

  /// 同步离线操作
  Future<void> _syncOfflineOperations() async {
    try {
      // 检查是否有待同步的离线操作
      if (await _offlineSyncService.hasPendingOperations()) {
        await _offlineSyncService.syncOfflineOperations();
      }
    } catch (e) {
      debugPrint('同步离线操作失败: $e');
      rethrow;
    }
  }

  /// 清理已同步的数据
  Future<void> _cleanupSyncedData() async {
    // 这里可以添加清理逻辑，比如删除已经成功同步的临时数据
    // 暂时留空，根据实际需求实现
  }

  /// 更新同步状态
  void _updateStatus(SyncStatus status) {
    _currentStatus = status;
    _syncStatusController.add(status);
  }

  /// 更新同步进度
  void _updateProgress(double progress) {
    _progressController.add(progress);
  }

  /// 释放资源
  void dispose() {
    _syncStatusController.close();
    _progressController.close();
  }
}
